/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package drivemachine;

import drivemachine.data2.CompareEntry;
import drivemachine.data2.Entry;
import drivemachine.data2.FolderEntry;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author positron
 */
public class DriveTreeModel implements TreeModel  {
	Entry s;
	TreeModelListener l;

	public void update(Entry s){
		this.s = s;
		//l.treeNodesInserted(new TreeModelEvent(s.root, new Object[]{s.root}));
		l.treeStructureChanged(new TreeModelEvent(s, new Object[]{s}) );
	}

	public DriveTreeModel() { }

	@Override
	public Object getRoot() {
		return s;
	}

	@Override
	public Object getChild(Object parent, int index) {
		//System.out.println(parent+" get "+index+" = "+((FolderEntry)parent).children.get(index));
		Entry e  = (Entry)parent;
		if(e instanceof CompareEntry && e.getSelfSize()==0) return e.getChild(index);
		if(index==0) return new SelfEntry(e.getSelfSize());
		return e.getChild(index-1);
	}

	@Override
	public int getChildCount(Object parent) {
		//System.out.println(parent+" childcount = "+((FolderEntry)parent).children.size());
		if(parent instanceof SelfEntry) return 0;
		Entry e = (Entry)parent;
		if(e instanceof CompareEntry && e.getSelfSize()==0) return e.getNumChildren();
		if(!e.hasChildren()) return 0;
		return e.getNumChildren()+1;
	}

	@Override
	public boolean isLeaf(Object parent) {
		//System.out.println(parent+" isleaf = "+!((FolderEntry)parent).hasChildren());
		if(parent instanceof SelfEntry) return true;
		Entry f = (Entry)parent;
		return !f.hasChildren();
	}

	@Override
	public int getIndexOfChild(Object parent, Object child) {
		//System.out.println(parent+" indexof "+child+" = " +((FolderEntry)parent).children.indexOf( ((FolderEntry)child) ) );
		if(child instanceof SelfEntry) return 0;
		//* should never happen
		if(parent instanceof SelfEntry) return 0;
		Entry e = (Entry)child;
		Entry p = (Entry)parent;
		if(e instanceof CompareEntry && e.getSelfSize()==0) return p.indexOfChild( e );
		return p.indexOfChild(e)+1;
	}

	@Override
	public void valueForPathChanged(TreePath path, Object newValue) {
        System.out.println("*** valueForPathChanged : " + path + " --> " + newValue);
	}

	@Override
	public void addTreeModelListener(TreeModelListener l) {
		this.l=l;
	}

	@Override
	public void removeTreeModelListener(TreeModelListener l) {
		this.l=null;
	}
	
	public static class SelfEntry {
		public final long size;
		public SelfEntry(long s) {size=s;}
		@Override
		public String toString() {
			return "<self> "+Entry.sizeToString(size);
		}
	}

}
